import { defineStore } from 'pinia'
import { ref } from 'vue'
import axios from 'axios'

export interface User {
  id: number
  username: string
  email: string
  role: string
  status: 'active' | 'inactive'
  createdAt: string
  updatedAt: string
  roles: Array<{
    id: number
    name: string
    code: string
    description?: string
  }>
}

export interface CreateUserForm {
  username: string
  email: string
  password: string
  role: string
}

export interface UpdateUserForm {
  id: number
  username?: string
  email?: string
  role?: string
  status?: 'active' | 'inactive'
  role_ids?: number[]
}

export const useUserStore = defineStore('user', () => {
  const users = ref<User[]>([])
  const loading = ref(false)
  const error = ref<string | null>(null)
  const total = ref(0)

  async function fetchUsers(params: {
    page?: number
    pageSize?: number
    search?: string
    role?: string
  } = {}) {
    loading.value = true
    error.value = null
    
    try {
      const response = await axios.get('/api/users/', { params })
      users.value = response.data.users
      total.value = response.data.total
      return { success: true }
    } catch (err: any) {
      error.value = err.response?.data?.message || '获取用户列表失败'
      return { success: false, error: error.value }
    } finally {
      loading.value = false
    }
  }

  async function createUser(userData: CreateUserForm) {
    loading.value = true
    error.value = null
    
    try {
      const response = await axios.post('/api/users/', userData)
      users.value.push(response.data)
      return { success: true, user: response.data }
    } catch (err: any) {
      error.value = err.response?.data?.message || '创建用户失败'
      return { success: false, error: error.value }
    } finally {
      loading.value = false
    }
  }

  async function updateUser(userData: UpdateUserForm) {
    loading.value = true
    error.value = null
    
    try {
      const response = await axios.put(`/api/users/${userData.id}`, userData)
      const index = users.value.findIndex(u => u.id === userData.id)
      if (index !== -1) {
        users.value[index] = response.data
      }
      return { success: true, user: response.data }
    } catch (err: any) {
      error.value = err.response?.data?.message || '更新用户失败'
      return { success: false, error: error.value }
    } finally {
      loading.value = false
    }
  }

  async function deleteUser(userId: number) {
    loading.value = true
    error.value = null
    
    try {
      await axios.delete(`/api/users/${userId}`)
      users.value = users.value.filter(u => u.id !== userId)
      return { success: true }
    } catch (err: any) {
      error.value = err.response?.data?.message || '删除用户失败'
      return { success: false, error: error.value }
    } finally {
      loading.value = false
    }
  }

  return {
    users,
    loading,
    error,
    total,
    fetchUsers,
    createUser,
    updateUser,
    deleteUser
  }
})
